<?php

namespace addons\kuerp\model;

use addons\kuerp\model\Staff;
use app\admin\model\kuerp\Commonseal;
use think\Model;
use addons\kuerp\model\Staff as StaffModel;
use app\admin\model\department\Admin as DepartmentAdmin;
use app\admin\model\ScoreApply;
use traits\model\SoftDelete;

class Flows extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'flows';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;
    const CONTRACT_STATUS='contract';
    const GOODSSALE_STATUS='goods_sale';
    const RECEIVABLES_STATUS='receivables';
    const CONSUME_STATUS='consume';
    const ACHIEVEMENT_STATUS='achievement';
    const APPROVAL_STATUS='approval';
    const QUOTE_STATUS='quote';
    const CARD_STATUS='card';//补卡
    const LEAVE_STATUS='leave';//请假
    const PARTS_STATUS='parts';//出入库
    const INVOICE_STATUS='invoice';//发票
    const DELIVERY_STATUS='delivery';//发货
    const INSTOCK_STATUS='instock';//入库
    const OUTSTOCK_STATUS='outstock';//出库
    const EXPENSE_STATUS='expense';//报销单
    const SCORE_STATUS='score';//积分申请
    const COMMON_SEAL='common_seal';//申请公章

    // 追加属性
    protected $append = [
        'relation_type_text'
    ];
    

    
    public function getRelationTypeList()
    {
        return ['goods_sale' => __('Goods_sale'), 'goods_purchase' => __('Goods_purchase'), 'goods_sales_exchange' => __('Goods_sales_exchange'), 'allocation' => __('Allocation'), 'expense' => __('Expense'), 'score' => __('Score')];
    }


    public function getRelationTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['relation_type']) ? $data['relation_type'] : '');
        $list = $this->getRelationTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    
    /**
     * 获取审批
     * @param $type
     * @return array|false
     */
    public static function getsteplist($type){
        $examineFlowData = Flows::getFlowByTypes($type);
        if (!$examineFlowData) {
            self::setdefault($type);
            $examineFlowData = Flows::getFlowByTypes($type);
        }

        $staff = Staff::info();
        $examine_ids = !empty($examineFlowData['flow_items']) ? json_decode($examineFlowData['flow_items'], true) : [];
        //获取数据提交人所在审核流程级数
        $examine_index = 0;
        foreach ($examine_ids as $key => $value) {
            if (in_array($staff->id, explode(',',$value['admin_id'])) ) {
                $examine_index = $key + 1;
                // break;
            }
        }
        //直接上级
        $parents = array_unique((new DepartmentAdmin())->getParentAdminIds($staff->id, true, true));
        //所有上级
        $parents1 = array_unique((new DepartmentAdmin())->getAllParentAdminIds($staff->id, true, true));
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        if (!empty($config_examine_admins)) {
            $config_parents = [];
            foreach ($config_examine_admins as $k => $v) {
                if (in_array($staff->id, explode(',', $v))) {
                    $config_parents[] = $k;
                }
            }
            $parents = array_unique(array_merge($parents, $config_parents));
            $parents1 = array_unique(array_merge($parents1, $config_parents));
        }

        $flow_staff_ids=[];
        //自选还是流程(1固定,0自选)
        // if ($examineFlowData['status'] == 1) {
            $pid = 0;//StaffModel::where(['id' => $staff->id])->value('parent_id');
            $stepList = [];
            foreach ($examine_ids as $ks => $vs) {
                //数据提交人在审批流程中，则他之前的审核步骤不需要
                if ($examine_index > 0 && $examine_index >= ($ks + 1)) {
                    continue;
                }
                $stepInfo = [];
                $stepInfo['order_id'] = $ks + 1;//第几级
                if ($vs['stafftype'] == 3) {//直属上级
                    $s = Admin::where(['id' => $pid])->field('id,nickname as name,avatar as img')->select();
                    $s = collection($s)->toArray();
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $pid;
                    $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$pid;
                } else if ($vs['stafftype'] == 1) {//指定员工(任意一人)
                    if ($ks == 0) {
                        $intersect = array_intersect($parents, explode(',',$vs['admin_id']));
                        if (empty($intersect)) {
                            $intersect = array_intersect($parents1, explode(',',$vs['admin_id']));
                        }
                    } else {
                        $intersect = array_intersect($parents1, explode(',',$vs['admin_id']));
                    }
                    $admin_ids = !empty($intersect) ? implode(',', $intersect) : $vs['admin_id'];
                    //并集
                    // $admin_ids = $ks == 0 ? implode(',', array_intersect($parents, explode(',',$vs['admin_id']))) : $vs['admin_id'];
                    $s = Admin::where(['id' => ['in', $admin_ids]])->field('id,nickname as name,avatar as img')->select();
                    $s = collection($s)->toArray();
                    foreach ($s as $k => $v) {
                        $img = cdnurl($v['img'], true);
                        $s[$k]['img'] = $img;
                    }
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $admin_ids;
                    $stepInfo['relation'] = 2;
                    $stepList[] = $stepInfo;
                    $flow_staff_ids[] = $admin_ids;

                } else {//指定员工(并签)
                    $s = Admin::where(['id' => ['in', $vs['admin_id']]])->field('id,nickname as name,avatar as img')->select();
                    $s = collection($s)->toArray();
                    foreach ($s as $k => $v) {
                        $img = cdnurl($v['img'], true);
                        $s[$k]['img'] = $img;
                    }
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['staffids'] = $vs['admin_id'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['relation'] = 1;
                    $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$vs['admin_id'];
                }
            }
        // } else {
        //     $stepList = [];
        // }
        $data = [];
        $data['flow_staff_ids'] = implode(',',$flow_staff_ids); //审批id
        $data['flow_id'] = $examineFlowData['id']; //审批id
        $data['order_id']=$stepList?$stepList[0]['order_id']:0;
        $data['status'] = 1;//$examineFlowData['status']; //1固定,0自选
        $data['stepList'] = $stepList ?: [];//审批流程
        return $data;
    }

    /**
     * 获取审批信息
     * @param $type
     * @return array|mixed
     */
    public static function getFlowByTypes($type)
    {
        $type = str_replace('contract','goods_sale', $type);
        $type = explode(',',$type);
        // $staff = Staff::info();
        // $type=explode('_',$type);
        // if ($type[0] == self::APPROVAL_STATUS) {
        //     $flow = FormApproval::where(['id' => $type[1]])->find();
        //     return $flow;
        // }
        $group_ids = '';//$staff->group_ids;
        $group_ids = explode(',', $group_ids);
        $flows = Flows::where(['relation_type' => $type[0], 'status' => 1])->order('id desc')->select();
        $flows = collection($flows)->toArray();
        $flow = [];
        foreach ($flows as $v) {
            if(empty($v['group_ids'])){
                $flow = $v;
                break;
            }
            $ids = explode(',', $v['group_ids']);
            if (array_intersect($group_ids, $ids)) {
                $flow = $v;
                break;
            }
        }
        return $flow;
    }

    /**
     * 设置默认
     */
    public static function setdefault($type)
    {
        switch ($type){
            case self::CONTRACT_STATUS:
                $name='订单审批';
                break;
            case self::EXPENSE_STATUS:
                $name='报销单审批';
                break;
            case self::COMMON_SEAL:
                $name='公章申请审批';
                break;
            // case self::QUOTE_STATUS:
            //     $name='报价单审批';
            //     break;
            // case self::RECEIVABLES_STATUS:
            //     $name='回款审批';
            //     break;
            // case self::CONSUME_STATUS:
            //     $name='费用审批';
            //     break;
            // case self::ACHIEVEMENT_STATUS:
            //     $name='业绩审批';
            //     break;
            // case self::CARD_STATUS:
            //     $name='补卡审批';
            //     break;
            // case self::LEAVE_STATUS:
            //     $name='请假审批';
            //     break;
            // case self::INVOICE_STATUS:
            //     $name='发票';
            //     break;
            default:
                $name='审批';
        }
        $data = [
            'name' => $name,
            'relation_type' => $type,
            'status' => 0,
            'examine_ids' => '[{}]',
            'group_ids' => '',
            'last_modified'=>time(),
            'last_admin_id'=>1,
        ];

        return (new self())->allowField(true)->save($data);
    }

    /**
     * 获取审批详情
     * @param $type
     * @return array|false
     */
    public static function getstepdetail($relation_type,$relation_id){
        switch ($relation_type){
            case self::GOODSSALE_STATUS:
                $model=new GoodsSales();
                break;
            case self::EXPENSE_STATUS:
                $model=new Expense();
                break;
            case self::SCORE_STATUS:
                $model=new ScoreApply();
                break;
            case self::COMMON_SEAL:
                $model=new Commonseal();
                break;
        }
        $row=$model->get($relation_id);
        if(empty($row)){
            return false;
        }
        $condition = false;
        $admin_id = 0;
        switch ($relation_type){
            case self::GOODSSALE_STATUS:
                $condition = $row['examine_status'] == 1;
                $admin_id = StaffMember::where('id', $row['sale_user'])->value('admin_id');//$row['preparation_id'];
                break;
            case self::EXPENSE_STATUS:
                $model=new Expense();
                $condition = $row['check_status'] == 2;
                $admin_id = $row['admin_id'];
                break;
            case self::SCORE_STATUS:
                $condition = $row['check_status'] == 2;
                $admin_id = $row['admin_id'];
                break;
            case self::COMMON_SEAL:
                $condition = $row['check_status'] == 2;
                $admin_id = $row['admin_id'];
                break;
        }
        $examineFlowData = Flows::withTrashed()->where(['relation_type'=>$relation_type])->find();
        if (!$examineFlowData) {
            //无可用审批流，请联系管理员
            return false;
        }
        // $staff_id=$row->create_staff_id??($row->staff_id??$row->owner_staff_id);
        $records=ExamineRecord::where(['relation_type'=>$relation_type,
            'relation_id'=>$relation_id])->field('createtime as check_time,examine_status as status,remark as content,admin_id,cur_index')->select();
        $records=collection($records)->toArray();
        $examineRecord=[];
        $indexRecord=[];
        foreach ($records as $v){
            $examineRecord[$v['admin_id']]=$v;
            $indexRecord[$v['cur_index']][] = $v['admin_id'];
        }
        $examine_ids = !empty($examineFlowData['flow_items']) ? json_decode($examineFlowData['flow_items'], true) : [];
        //获取数据提交人所在审核流程级数
        $examine_index = 0;
        foreach ($examine_ids as $key => $value) {
            if (in_array($admin_id, explode(',',$value['admin_id'])) ) {
                $examine_index = $key + 1;
                // break;
            }
        }
        // dump($examine_ids);
        //获取该记录的上级
        //直接上级
        $parents = array_unique((new DepartmentAdmin())->getParentAdminIds($admin_id, true, true));
        //所有上级
        $parents1 = array_unique((new DepartmentAdmin())->getAllParentAdminIds($admin_id, true, true));
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        if (!empty($config_examine_admins)) {
            $config_parents = [];
            foreach ($config_examine_admins as $k => $v) {
                if (in_array($admin_id, explode(',', $v))) {
                    $config_parents[] = $k;
                }
            }
            $parents = array_unique(array_merge($parents, $config_parents));
            $parents1 = array_unique(array_merge($parents1, $config_parents));
        }
        $flow_staff_ids = [];
        //自选还是流程(1固定,0自选)
        if ($examineFlowData['status'] == 1) {
            $pid = 0;//StaffModel::where(['id' => $staff->id])->value('parent_id');
            $stepList = [];
            foreach ($examine_ids as $ks => $vs) {
                //数据提交人在审批流程中，则他之前的审核步骤不需要
                if ($examine_index > 0 && $examine_index >= ($ks + 1)) {
                    continue;
                }
                $stepInfo = [];
                $stepInfo['order_id'] = $ks + 1;//第几级
                if ($vs['stafftype'] == 3) {//直属上级
                    $s = Admin::where(['id' => $pid])->field('id,nickname as name,avatar as img')->select();
                    $s = collection($s)->toArray();
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $pid;
                    // $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$pid;
                } else if ($vs['stafftype'] == 1) {//指定员工(任意一人)
                    if ($ks == 0) {
                        $intersect = array_intersect($parents, explode(',',$vs['admin_id']));
                        if (empty($intersect)) {
                            $intersect = array_intersect($parents1, explode(',',$vs['admin_id']));
                        }
                    } else {
                        $intersect = array_intersect($parents1, explode(',',$vs['admin_id']));
                    }
                    if (!empty($indexRecord[$ks + 1])) {
                        $intersect = array_intersect($intersect, $indexRecord[$ks + 1]);
                    }
                    $admin_ids = !empty($intersect) ? implode(',', $intersect) : $vs['admin_id'];
                    //并集
                    // $admin_ids = $ks == 0 ? implode(',', array_intersect($parents, explode(',',$vs['admin_id']))) : $vs['admin_id'];
                    $s = Admin::where(['id' => ['in', $admin_ids]])->field('id,nickname as name,avatar as img')->select();
                    $s = collection($s)->toArray();
                    foreach ($s as $k => $v) {
                        $img = cdnurl($v['img'], true);
                        $s[$k]['img'] = $img;
                    }
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $admin_ids;
                    $stepInfo['relation'] = 2;
                    // $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$admin_ids;

                } else {//指定员工(并签)
                    $s = Admin::where(['id' => ['in', $vs['admin_id']]])->field('id,nickname as name,avatar as img')->select();
                    $s = collection($s)->toArray();
                    foreach ($s as $k => $v) {
                        $img = cdnurl($v['img'], true);
                        $s[$k]['img'] = $img;
                    }
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['staffids'] = $vs['admin_id'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['relation'] = 1;
                    // $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$vs['admin_id'];
                }

                //审批记录
                foreach ($stepInfo['stafflist'] as &$staffinfo) {
                    if (!empty($examineRecord[$staffinfo['id']]) && $examineRecord[$staffinfo['id']]['cur_index'] == $stepInfo['order_id']) {
                        $staffinfo['examine_reord'] = $examineRecord[$staffinfo['id']];
                        $staffinfo['examine_reord']['status_text'] = $examineRecord[$staffinfo['id']]['status'] == 1 ? '审核通过' : '审核拒绝';
                    } else {
                        //原有订单已审核 没有审核记录 最后一级显示审核通过
                        if($stepInfo['order_id'] == count($examine_ids) && $condition) {
                            $staffinfo['examine_reord'] = ['status' => 1, 'check_time' => '', 'content' => '','status_text'=>'审核通过'];
                        } else {
                            $staffinfo['examine_reord'] = ['status' => 0, 'check_time' => '', 'content' => '','status_text'=>'待审核'];
                        }
                    }
                }
                $stepList[] = $stepInfo;

                // 更新审批状态
                foreach ($stepList as $order_id => &$step) {
                    $approved = false;
                    foreach ($step['stafflist'] as &$staff) {
                        if ($staff['examine_reord']['status'] == 1) {
                            $approved = true;
                            break;
                        }
                    }

                    if ($approved) {
                        // 当前级别有已审核
                        foreach ($step['stafflist'] as &$staff) {
                            if ($staff['examine_reord']['status'] == 0) {
                                $staff['examine_reord']['status_text'] = '已跳过';
                            }
                        }

                        // 更新下一级别的状态
                        for ($i = $order_id - 1; $i >= 0; $i--) {
                            foreach ($stepList[$i]['stafflist'] as &$staff) {
                                if ($staff['examine_reord']['status'] == 0) {
                                    $staff['examine_reord']['status_text'] = '已跳过';
                                }
                            }
                        }
                    }
                }
            }
        } else {
            $stepList = [];
        }


        $data = [];
        $data['flow_id'] = $examineFlowData['id']; //审批id
        $data['flow_staff_ids'] = implode(',',$flow_staff_ids); //审批id
        $data['order_id'] = $stepList?$stepList[0]['order_id']:0;
        $data['status'] = $examineFlowData['status']; //1固定,0自选
        $data['stepList'] = $stepList ?: [];//审批流程
        return $data;
    }

    /**
     * 给下一审批人发送审批通知
     */
    public static function sendStepRecord($flow,$relation_type,$relation_id,$check_staff_ids='', $check_step_sort = 0){
        $staff = Staff::info();
        if(!is_array($check_staff_ids)){
            $check_staff_ids=explode(',',$check_staff_ids);
        }
        $flow['flow_items'] = is_array($flow['flow_items']) ? $flow['flow_items'] : json_decode($flow['flow_items'], true);
        // if($flow['status'] == 0){//发起人自选

        //     $diff              = array_diff(explode(',',$flow['flow_staff_ids']), $check_staff_ids);
        //     if(empty($diff)){
        //         return ['status'=>true,'order_id'=>1];
        //     }else{
        //         $diff=array_values($diff);
        //         ExamineRecord::addExaminse($relation_type,$relation_id, $diff[0]);

        //         return ['status'=>false,'order_id'=>1];
        //     }
        // }
        foreach ($flow['flow_items'] as $k => $v){
                //审批步骤小于等于当前步骤 跳过通知
                if ($check_step_sort > 0 && $k <= ($check_step_sort - 1)) {
                    continue;
                }
            $staffIds= $k == 0 && $check_step_sort == 0 ? array_intersect($staff->parentids, explode(',',$v['admin_id'])) : explode(',',$v['admin_id']);//explode(',',$v['admin_id']);
            $is_check=0;//是否通过
            if($v['stafftype'] == 1){//任意一人 或签
                foreach ($staffIds as $sid) {
                    if (in_array($sid, $check_staff_ids)) {
                        $is_check = 1;
                    }
                }

            }else{//直属上级和并签
                $is_check = 1;
                foreach ($staffIds as $sid) {
                    if (!in_array($sid, $check_staff_ids)) {
                        $is_check = 0;
                    }
                }
            }
            if ($is_check != 1) {//发送审批通知
                foreach ($staffIds as $sid) {
                    if (!in_array($sid, $check_staff_ids)) {
                            //发送通知
                            Message::addMessage(Message::EXAMINE_TYPE, $relation_id, $sid, $staff->id);
                        //    ExamineRecord::addExaminse($relation_type, $relation_id, $sid);
                    }
                }
                return ['status'=>false,'order_id'=>$k+1];
            }

        }

        return ['status'=>true,'order_id'=>count($flow['flow_items'])];
    }

}
